//二次封装axios
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { localSet, localGet, localRemove } from '@/utils/utils'
import useUserStore from '@/store/modules/user'
//创建axios实例
const request = axios.create({
  //基础路径
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
})
//添加拦截器
request.interceptors.request.use((config) => {
  const token = localGet('TOKEN')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
//响应拦截器
request.interceptors.response.use(
  (response) => {
    const userStore = useUserStore()
    //把请求头中的token放入data
    const token = response.headers.authorization
    if (token) {
      localSet('TOKEN', token)
      userStore.token = token
    }
    //简化数据
    return response.data
  },
  (error) => {
    const userStore = useUserStore()
    let message = ''
    //http状态码
    const status = error.response.status
    switch (status) {
      case 401:
        message = 'TOKEN过期'
        localRemove('TOKEN')
        userStore.token = ''
        router.push('/login')
        break
      case 403:
        message = '无权访问'
        break
      case 404:
        message = '请求地址错误'
        break
      case 500:
        message = '服务器出现问题'
        break
      default:
        message = '网络出现问题'
        break
    }
    ElMessage({
      type: 'error',
      message,
    })

    return Promise.reject(error)
  },
)

export default request
